package server;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Context {
    private String appBase;
    private String contextName;

    private Map<String, Wrapper> wrapperMap;

    private MiniClassLoader miniClassLoader;

    public Context(String appBase, String contextName) {
        this.appBase = appBase;
        this.contextName = contextName;
        wrapperMap = new HashMap<>();
    }

    public void init() throws IOException, ClassNotFoundException, InstantiationException, IllegalAccessException {
        try {
            miniClassLoader = new MiniClassLoader();

            System.out.println("---miniClassLoader[" +
                            miniClassLoader.toString() + "]->" +miniClassLoader.getParent().toString());
            //加载context对应的文件夹下面的所有的class
            miniClassLoader.loadClassesFromBasePath(appBase + File.separator + contextName);

            loadServlet(miniClassLoader);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }

    public void start() {
        //什么都不做,仅为了模拟tomcat的Lifecycle接口
    }

    private void loadServlet(MiniClassLoader miniClassLoader) throws FileNotFoundException, InstantiationException, IllegalAccessException, ClassNotFoundException {
        File webConfigFile = new File(this.appBase + File.separator
                + this.contextName + File.separator + "web.xml");

        InputStream resourceAsStream =  new FileInputStream(webConfigFile);
        SAXReader saxReader = new SAXReader();

        try {
            Document document = saxReader.read(resourceAsStream);
            Element rootElement = document.getRootElement();

            List<Element> selectNodes = rootElement.selectNodes("//servlet");
            for (int i = 0; i < selectNodes.size(); i++) {
                Element element =  selectNodes.get(i);

                // <servlet-name>lagou</servlet-name>
                Element servletnameElement = (Element) element.selectSingleNode("servlet-name");
                String servletName = servletnameElement.getStringValue();

                // <servlet-class>server.LagouServlet</servlet-class>
                Element servletclassElement = (Element) element.selectSingleNode("servlet-class");
                String servletClass = servletclassElement.getStringValue();

                // 根据servlet-name的值找到url-pattern
                Element servletMapping = (Element) rootElement.selectSingleNode("/web-app/servlet-mapping[servlet-name='" + servletName + "']");
                // /lagou
                String urlPattern = servletMapping.selectSingleNode("url-pattern").getStringValue();

                // 从class文件中创建class
                HttpServlet httpServlet = (HttpServlet) miniClassLoader.loadClass(servletClass).newInstance();

                Wrapper wrapper = new Wrapper(httpServlet);
                wrapperMap.put(urlPattern, wrapper);

            }
        } catch (DocumentException e) {
            e.printStackTrace();
        }
    }

    public void process(Request request, Response response, MappedData mappedData) throws Exception {
        Wrapper wrapper = wrapperMap.get(mappedData.getMappedUrlPattern());
        if (wrapper == null) {
            throw new MappingException();
        }

        wrapper.process(request, response);
    }
}
